const arr = [
  {
    id: 1,
    name: 'a'
  },
  {
    id: 2,
    name: 'b',
    parentId: 1
  },
  {
    id: 3,
    name: 'c',
    parentId: 1
  },
  {
    id: 4,
    name: 'd',
    parentId: 2
  },
  {
    id: 5,
    name: 'e',
    parentId: 2
  },
  {
    id: 6,
    name: 'f',
    parentId: 4
  },
];

const trans = function (arr) {
  const factory = {};
  arr.forEach(function (item) {
    factory[item.id] = item;
  });
  const rootArr = [];
  arr.forEach(function (item) {
    if (item.parentId) {
      if (factory[item.parentId]) {
        if(!factory[item.parentId].children){
          factory[item.parentId].children = {};
        }
        factory[item.parentId].children[item.id] = item;
      } else {
        rootArr.push(item);
        console.warn('未找到父亲id, ' + item);
      }
    }else{
      rootArr.push(item);
    }
  });
  return rootArr;
};
const rootArr = trans(arr);
console.log(JSON.stringify(rootArr[0], function (key, value) {
  // console.log(key, value);
  if(key === '4'){ //可以把这条数据过滤掉
    return;
  }
  return value;
}, 2));
